<?php

namespace App\AdminModule\Presenters;

use \Nette\Application\UI\Form,
    \Nette\Utils\Image,
    \Nette\Utils\Strings,
    \Nette\Utils\Html,
    \Grido, 
    \Grido\Grid,
    App\Model\Dao\Photo;
/**
 * Photo presenter.
 */
class PhotoPresenter extends BasePresenter {
 
  /** @var \Kdyby\Doctrine\EntityManager @inject */
  public $em;
  
  /**
   * Add photo form
   * @param String $name
   * @return \Nette\Application\UI\Form
   */
  public function createComponentAddPhotoForm($name){
    $form = new Form();
    $form->addText('name', 'Název')->addRule(Form::FILLED, 'Název musí být vyplněn');
    $form->addUpload('photo', 'Obrázek - JPEG')
        ->addRule(Form::FILLED, 'Obrázek musí být vložen')
        ->addRule(Form::IMAGE, 'Soubor musí být obrázek');
    $form->addSubmit('send');
    $form->onSuccess[] = callback($this, 'addPhotoFormSuccess');
    
    return $form;
  }
  
  /**
   * Delete photo
   * @param int $id
   * @return boolean
   */
  public function handleDelete($id){
    if(!$this->user->isInRole('admin')){
      return;
    }
    
    $photoDao = $this->em->getDao(Photo::getClassName());
    $p = $photoDao->find($id);
    $hash = $p->getFile();
    @unlink(ROOT_DIR . '/content/photos/' . $hash . '/image.jpg');
    @rmdir(ROOT_DIR . '/content/photos/' . $hash);
    $this->em->remove($p);
    $this->em->flush();
    $this->redirect('Photo:default');
  }
  
  /**
   * Photo grid
   * @param String $name
   * @return \Grido\Grid
   */
  public function createComponentPhotoGrid($name){
    $g = new Grid($this, $name);
    
    $qb = $this->em->createQueryBuilder()
      ->addSelect('p.file AS file1')
      ->addSelect('p.file AS file2')
      ->addSelect('p.id AS id')
      ->addSelect('p.name AS name')
      ->from(Photo::getClassName(), ' p');
    
    $photos =  $qb->getQuery()->getArrayResult();

    // Grido data
    $g->model = $photos;    
    
    $g->addColumnText('id', 'ID')
        ->setSortable()
        ->setFilterText();
    $g->addColumnText('file1', 'Obrázek')
        ->setSortable()
        ->setFilterText();
    $g->addColumnText('name', 'Název')
        ->setSortable()
        ->setFilterText();
    $g->addColumnText('file2', 'URL')
        ->setSortable()
        ->setFilterText();
    
    $basePath = 'http://' . $_SERVER['SERVER_NAME']; //only on production works
    $g->getColumn('file1')->setCustomRender(function($item) use($basePath){
      $url = $basePath . '/content/photos/' . $item['file1'] . '/image.jpg';
      return Html::el('img', array('src' => $url, 'width' => '150'));
    });
    
    $g->getColumn('file2')->setCustomRender(function($item) use($basePath){
      return $basePath . '/content/photos/' . $item['file1'] . '/image.jpg';
    });

    if($this->user->isInRole('admin')){
      // Create delete button
      $g->addActionHref('delete', 'Smazat', 'delete!')
        ->setIcon('remove')->setPrimaryKey('id');
    }
    
    // Return grido
    $g->filterRenderType = Grido\Components\Filters\Filter::RENDER_INNER;
    $g->setExport();
    return $g;
  }
  
  /**
   * Add photo form execute
   * @param Form $form
   */
  public function addPhotoFormSuccess($form){
    $values = $form->getValues();
    
    if ($values['photo']->name != "" && $values['photo']->isImage()) {
			$hash = $this->savePicture($values['photo']);
      
      $photo = new Photo();
      $photo->setFile($hash);
      $photo->setName($values['name']);
      
      $this->em->persist($photo);
      $this->em->flush();
      
      $this->flashMessage('Obrázek byl nahrán', 'success');
		}else{
      $this->flashMessage('Nahrávání se nezdařilo', 'danger');
    }
    
    $this->redirect('Photo:default');
  }
  
  /**
   * Save photo
   * @param Image $picture
   * @return string
   */
  private function savePicture($picture){
    $temp = $picture->getTemporaryFile();
		$image = Image::fromFile($temp);

		$hash = Strings::random(10) . time();
		$path = ROOT_DIR . '/content/photos/' . $hash;
		mkdir($path);
		$image->save($path . '/image.jpg');

		return $hash;
  }
}
